<?php
namespace app\tuchuang\controller;

use app\common\controller\Front;

class Index extends Front
{
    //远程图片
    private $imageUrl   = '';
    //允许类型
    private $imageType  = [];
    //图片内型contentType
    private $mimeType   = '';
    //图片内容
    private $imgContent = '';
    //临时文件名
    private $fileName   = 'images';

	public function _initialize()
    {
        $this->imageUrl  = DcEmpty(config('tuchuang.link_default'), 'https://cdn.daicuo.cc/images/gzh/dc_01.jpg');
        
        $this->imageType = config('tuchuang.mime_type');
        
		parent::_initialize();
	}
    
    //图床首页
	public function index()
    {
        $this->assign('path_upload',url('tuchuang/apis/upload',false,false));
        
		return $this->fetch();
	}
    
    //解析API自定义加密
    public function read()
    {
        $this->imgDetail(input('url/s'));
	}
    
    //解析base64编码
    public function base64()
    {
        if(!in_array('base64', explode(',',config('tuchuang.parse_action')))){
            $this->redirect($this->imageUrl, 302);
        }
        
        config('tuchuang.link_decode','base64_decode');
        
        $this->imgDetail(input('url/s'));
    }
    
    //解析urlencode/rawurlencode编码
    public function rawurl()
    {
        if(!in_array('rawurl', explode(',',config('tuchuang.parse_action')))){
            $this->redirect($this->imageUrl, 302);
        }
        
        config('tuchuang.link_decode','rawurldecode');
        
        $this->imgDetail(input('url/s'));
    }
    
    //解析DcDesDecode编码（呆错后台管理框架默认加密）
    public function daicuo()
    {
        if(!in_array('daicuo', explode(',',config('tuchuang.parse_action')))){
            $this->redirect($this->imageUrl, 302);
        }
        
        config('tuchuang.link_decode','DcDesDecode');
        
        $this->imgDetail(input('url/s'));
    }
    
    //空操作
    public function _empty($name)
    {
        if( in_array($name,['change','parse','upload']) ){
            config('common.app_domain',true);
            return $this->fetch();
        }
        return lang('error');
	}
    
    //公共解析直接输出图片
    private function imgDetail($imgUrl='')
    {
        //解密地址
        $imgUrl = $this->urlDecode($imgUrl);

        //验证协议
        $args = parse_url($imgUrl);
        if(!in_array($args['scheme'], array('http','https','ftp'))){
            $this->redirect($this->imageUrl, 302);
        }
        
        //验证访问域名
        if( config('tuchuang.link_domain') ){
            //无来路时
            if(!$referer = input('server.HTTP_REFERER')){
                $this->redirect($imgUrl, 302);
            }
            //未在授权名单
            if( !in_array(parse_url($referer, PHP_URL_HOST), explode(',', config('tuchuang.link_domain'))) ){
                $this->redirect($imgUrl, 302);
            }
        }
        
        //验证加速域名
        if( config('tuchuang.link_referer') ){
            $referers = explode(',', config('tuchuang.link_referer'));
            if( !in_array($args['host'], $referers) ){
                $this->redirect($imgUrl, 302);
            }
        }
        
        //图片缓存状态
        if(config('tuchuang.cache_time') > 0){
            return $this->imgCache($imgUrl);
        }elseif(config('tuchuang.cache_time') < 0){
            return $this->imgFile($imgUrl);
        }else{
            $this->curl($imgUrl);
            return $this->imgEcho();
        }
	}
    
    //图片保存到缓存
    private function imgCache($imgUrl='')
    {
        //图片缓存相关
        $this->fileName = md5($imgUrl);
        //是否启缓缓存
        $cacheTime = config('tuchuang.cache_time');
        //优先缓存读取(图片内型与图片内容)
        $imgCache = DcCache($this->fileName);
        if($imgCache['mimeType'] && $imgCache['imgContent']){
            $this->mimeType   = $imgCache['mimeType'];
            $this->imgContent = $imgCache['imgContent'];
        }else{
            //CURL请求远程图片
            $this->curl($imgUrl);
            //将图片缓存到本地
            if($this->imgContent && $this->mimeType){
                DcCache($this->fileName, ['mimeType'=>$this->mimeType,'imgContent'=>$this->imgContent], intval($cacheTime));
            }
        }
        //输出图片
        return $this->imgEcho();
	}
    
    //图片保存到本地
    private function imgFile($imgUrl='')
    {
        //md5文件名
        $this->fileName = md5($imgUrl);
        //保存文件名
        $saveName = ltrim(config('common.upload_path'), '/').'/'.substr($this->fileName,0,4).'/'.$this->fileName;
        //实例化文件操作类
        $file = new \files\File();
        //判断文件是否存在
        if($file->f_has($saveName)){
            $this->mimeType   = imgMimeType($saveName);
            $this->imgContent = $file->read($saveName);
        }else{
            //CURL请求远程图片
            $this->curl($imgUrl);
            //下载远程图片到本地
            if($this->imgContent && in_array($this->mimeType, $this->imageType)){
                //保存远程图片
                $file->write($saveName, $this->imgContent);
                //保存图片信息
                imgInfoInsert($this->site['user']['user_id'], $this->fileName, $this->mimeType, strlen($this->imgContent), $imgUrl);
            }
        }
        //输出图片
        return $this->imgEcho();
    }
    
    //输出图片
    private function imgEcho()
    {
        //文件类型验证
        if( !in_array($this->mimeType, $this->imageType) ){
            $this->redirect($this->imageUrl, 302);
        }
        //文件内容验证
        if(!$this->imgContent){
            $this->redirect($this->imageUrl, 302);
        }
        //ETAG浏览器缓存
        $iftag = isset($_SERVER['HTTP_IF_NONE_MATCH']) ? $_SERVER['HTTP_IF_NONE_MATCH'] == $this->fileName : null;
        if($iftag){
            header('HTTP/1.0 304 Not Modified');
            exit();
        }
        //header头
        header('Content-type: '.$this->mimeType);
        //浏览器缓存标识
        header('ETag: '.$this->fileName);
        //图片内容
        exit($this->imgContent);
    }
    
    //图片地址解密处理
    private function urlDecode($imgUrl){
        if(!$imgUrl){
            return $this->imageUrl;
        }
        if( config('tuchuang.link_decode') ){
            foreach( explode(',', config('tuchuang.link_decode')) as $key=>$function){
                $imgUrl = $function($imgUrl);
            }
        }
        return DcEmpty($imgUrl, $this->imageUrl);
    }
    
    //CURL获取文件内容
    private function curl($url='')
    {
        $ch = curl_init();
        curl_setopt ($ch, CURLOPT_URL, $url);
        curl_setopt ($ch, CURLOPT_HEADER, 0);
        curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); 
        curl_setopt ($ch, CURLOPT_TIMEOUT, 10);
        curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT,10);
        curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt ($ch, CURLOPT_ENCODING, "");
        //https自动处理
        $http = parse_url($url);
        if($http['scheme'] == 'https'){
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        }
        //设置图片内容
        $this->imgContent = curl_exec($ch);
        //设置图片类型（CONTENT_TYPE）
        $contentType      = explode(";", curl_getinfo($ch, CURLINFO_CONTENT_TYPE));
        $this->mimeType   = $contentType[0];
        //关闭链接
        curl_close($ch);
    }
}